package com.aaa.sbm.service;

import com.aaa.sbm.entity.Order;
import com.aaa.sbm.esdao.OrderDao;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    /**
     * 依赖注入orderDao
     */
    @Autowired
//    @Resource(name = "",type = "")
    private OrderDao orderDao;

    @Override
    public List<Order> queryInEs(int type, String propertyName, String value) {
        //封装查询条件对象
        QueryBuilder queryBuilder=null;
        if(type==1){
            //查询全部数据GET   /index_order/_search  select * from Order
            queryBuilder= QueryBuilders.matchAllQuery();
        }else if(type==2 && !StringUtils.isEmpty(propertyName) &&
                    !StringUtils.isEmpty(value)){
            //matchQuery 按照列和值进行查询   /index_order/_search?q=goodId:1001
            // select * from Order where propertyName=#{value}
            queryBuilder=QueryBuilders.matchQuery(propertyName,value);
        }else if(type==3 && !StringUtils.isEmpty(value)){
            //multiMatchQuery  select * from Order where orderNo=#{value} or orderName#{value}
            //   select * from user where telnum="1666666668" or userName="1666666668" or email="1666666668"
            queryBuilder=QueryBuilders.multiMatchQuery(value,"orderNo","orderName");
        }else if(type==4 && !StringUtils.isEmpty(propertyName) &&
                !StringUtils.isEmpty(value)){
            //wildcardQuery  oracle  select * from Order where propertyName like '%'||#{value}||'%'
            //               mysql   select * from Order where propertyName like concat('%',#{value},'%')
            queryBuilder=QueryBuilders.wildcardQuery(propertyName,"*"+value+"*");
        }


        //根据查询条件查询
        Iterable<Order> orderIterable = orderDao.search(queryBuilder);
        //Iterable转Iterator
        Iterator<Order> iterator = orderIterable.iterator();
        //实例化List<Order>集合对象
        List<Order> orderList=new ArrayList<>();
        //循环迭代器
        while (iterator.hasNext()){
            Order order = iterator.next();
            orderList.add(order);
        }
        return orderList;
    }

    @Override
    public int addOrUpdate(Order order) {
        Order rorder=orderDao.save(order);
        if(rorder!=null){
            return 1;
        }
        return 0;
    }

    @Override
    public int deleteById(long id) {
        try {
            orderDao.deleteById(id);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
